<?php
namespace app\admin\service;
use app\admin\model\User;
use app\admin\traits\Result;
use think\facade\Request;

class UserService
{
    use Result;
    
    
    public static function edit($data)
    {
        //验证数据合法性
        $validate = validate('User');
        if (!$validate->scene('edit')->check($data)) {
            //令牌数据无效时重置令牌
            $validate->getError() != '令牌数据无效' ? $token = Request::token() : $token = '';
            $msg = Result::error($validate->getError(), null, ['token' => $token]);
            return $msg;
        }
       if(empty($data['password'])){
           unset($data['password']);
       }else{
           $pass_key = self::str_rand(10);
           $data['pass_key']= $pass_key;
           $data['password'] = md5($data['password'].$pass_key);
       }
    
        $res = User::update($data, ['uid' => $data['uid']]);
        if ($res) {
            $msg = Result::success('编辑成功', url('/admin/user-userlist'));
        } else {
            $msg = Result::error('编辑失败');
        }
        return $msg;
    }

    public static function add($data)
    {
        //验证数据合法性
        $validate = validate('User');
        if (!$validate->scene('add')->check($data)) {
            //令牌数据无效时重置令牌
            $validate->getError() != '令牌数据无效' ? $token = Request::token() : $token = '';
            $msg = Result::error($validate->getError(), null, ['token' => $token]);
            return $msg;
        }

        $user = new User;
        $user->username = $data['username'];
        $user->name = $data['name'];
        $pass_key = self::str_rand(10);
        $user->pass_key = $pass_key;
        $user->password  = md5($data['password'].$pass_key);
        $user->create_time = time();
        $res = $user->save();
        if ($res) {
            $msg = Result::success('添加成功', url('/admin/user-userlist'));
        } else {
            $msg = Result::error('添加失败');
        }
        return $msg;
    }
    /**
     * 生成指定长度随机字符串
     * @param int $length
     * @param string $char
     * @return bool|string
     */
    static function str_rand($length = 32, $char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
        if(!is_int($length) || $length < 0) {
            return false;
        }
        $string = '';
        for($i = $length; $i > 0; $i--) {
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $string;
    }
}

?>